import { shallowRef } from 'vue'
import { useTemperature } from './useTemperature'
import { usePressure } from './usePressure'
import { useOilPressure } from './useOilPressure'
import { useCasingPressure } from './useCasingPressure'
import { useDiffPressure } from './useDiffPressure'
import { useFlow } from './useFlow'
import { useTotalFlow } from './useTotalFlow'
import { baseWSURL } from '../api/ws'
import screenfull from 'screenfull'
import router from '../router'

const { updateTemperature } = useTemperature()
const { updatePressure } = usePressure()
const { updateOilPressure } = useOilPressure()
const { updateCasingPressure } = useCasingPressure()
const { updateDiffPressure } = useDiffPressure()
const { updateFlow } = useFlow()
const { updateTotalFlow } = useTotalFlow()
const socket = shallowRef()
const alarmAudioRef = shallowRef()

function openSocket() {
  const user = JSON.parse(localStorage.getItem('user'))
  const socketUrl = `${baseWSURL}/chart/${user.id}`
  if (!socket.value) {
    socket.value = new WebSocket(socketUrl, [localStorage.getItem('token')])
  }
  //打开事件
  socket.value.onopen = function () {
    console.log('图表websocket已打开')
  }
  //获得消息事件
  socket.value.onmessage = (msg) => {
    const data = JSON.parse(msg.data)
    if (data.type === 'instant') {
      // 如果有异常数据，播放报警音频
      if (data.realData.status !== -1) {
        playAlarmAudio()
      }
      dispatchData(data.time, data.realData)
    }
  }
  //关闭事件
  socket.value.onclose = function () {
    console.log('图表websocket已关闭')
  }
  //发生了错误事件
  socket.value.onerror = function () {
    closeSocket()
    console.log('图表websocket发生了错误')
  }
}
function closeSocket() {
  if (socket.value) {
    socket.value.close()
    socket.value = null
  }
}
function dispatchData(time, realData) {
  updateTemperature(time, realData.temperature, realData.status & 1)
  updatePressure(realData.pressure, (realData.status >> 1) & 1)
  updateOilPressure(realData.oilPressure, (realData.status >> 2) & 1)
  updateCasingPressure(realData.casingPressure, (realData.status >> 3) & 1)
  updateDiffPressure(realData.diffPressure, (realData.status >> 4) & 1)
  updateFlow(time, realData.flow, (realData.status >> 5) & 1)
  updateTotalFlow(time, realData.totalFlow, (realData.status >> 6) & 1)
}
function registerAlarmAudio(audio) {
  alarmAudioRef.value = audio
}
function playAlarmAudio() {
  alarmAudioRef.value.playbackRate = 2
  alarmAudioRef.value.play()
}
function toggleFullScreen() {
  if (!screenfull.isFullscreen) {
    router.replace('/fullScreen')
  } else {
    router.replace('/index')
  }

  if (screenfull.isEnabled) {
    screenfull.toggle()
  }
}

export const useChart = () => {
  return {
    openSocket,
    closeSocket,
    registerAlarmAudio,
    playAlarmAudio,
    toggleFullScreen
  }
}
